/*
 ****************************
 *  发布订阅模式
 ****************************
 */
(function($) {
    var o = $({}); //自定义事件对象
    $.each({
        trigger: 'publish',
        on: 'subscribe',
        off: 'unsubscribe'
    }, function(key, val) {
        jQuery[val] = function() {
            o[key].apply(o, arguments);
        };
    });
})(jQuery);

/*
 ****************************
 *  预加载器
 ****************************
 */

var Loader = (function() {

    //数据预加载
    var manifest = [];

    var preload;

    //定义相关JSON格式文件列表
    function setupManifest() {

        var imgs = $('.preload-imgs img'),
            el = null;
        for (var i = 0; i < imgs.length; i++) {

            el = $(imgs[i]);
            if (el.attr('data-type') == 'javascript') {
                manifest.push({
                    id: el.attr('data-id'),
                    src: el.attr('data-src'),
                    frame: el.attr('data-frame') - 1
                });
            } else if (el.attr('data-type') == 'sound') {
                manifest.push({
                    id: el.attr('data-id'),
                    src: el.attr('data-src')
                });
            } else {
                manifest.push({
                    id: 'img' + i,
                    src: imgs[i].getAttribute('data-src')
                });
            }

        }
    }
    //开始预加载
    function startPreload() {
        preload = new createjs.LoadQueue(true);
        preload.installPlugin(createjs.Sound, {
            loop: -1
        });
        preload.setMaxConnections(50);
        preload.on("progress", handleFileProgress);
        preload.on("complete", loadComplete);
        preload.on("error", loadError);
        preload.loadManifest(manifest);

    }

    duration = null;
    //处理单个文件加载
    function handleFileLoad(event) {
        if (event.item.type == "javascript") {
            FRAMES[event.item.frame] = FRAMES[event.item.frame].concat(window[event.item.id])
            delete window[event.item.id];
        } else if (event.item.type == "sound") {
            duration = event.result.duration;
        }
    }

    //处理加载错误：大家可以修改成错误的文件地址，可在控制台看到此方法调用
    function loadError(evt) {
        console.log(evt);
    }

    //已加载完毕进度
    var precentNode = $('.load-mark');

    function handleFileProgress(event) {
        var precent = Math.round(preload.progress * 100);
        precentNode.find('i').text(precent + '%');
    }

    //全部资源加载完毕
    function loadComplete(event) {
        $(".load-mark i,.load-icon1,.load-icon2").hide();
        $(".btn").fadeIn(1000);
    }

    function init() {
        setupManifest();
        startPreload();
    }
    return {
        init: init
    }

})();


window.requestAnimFrame = (function() {
    return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
            window.setTimeout(callback, 1000 / 30);
        };
})();

/*
 ****************************
 *  定义帧动画
 ****************************
 */

//定义页面
var page = {
    init: function() {
        setTimeout(function() {
            $(".phone-top").addClass("active");
            setTimeout(function() {
                $(".hand").show();
            },1000)
        },1000)

        // Loader.init();
        // this.fixVideo();
        this._bindEvent();
    },
    fixVideo: function () {
        var width = $(window).width(),
            height = $(window).height();
        var scaleX = width / 608,
            scaleY = height / 1080;
        $("#framesBox").css("transform","scaleX(" + scaleX + ") scaleY(" + scaleY + ")");
    },
    //绑定事件
    _bindEvent: function() {
        var _self = this;
        var width = $(window).width();
        var height = $(window).height();
        $(".phone-top").bind('touchstart', function() {
            $(".first-page").hide();
            $(".load-mark").show();
            Loader.init();
        });
        //播放视频1
        $.subscribe("playVideo1", function(e) {
            $("#video1").css({
                width: width,
                height: height
            })
            var video = $("#video1")[0];

            video.play();

            video.addEventListener("ended",function(){
                _self._showPhone();
                $("#video1").remove();
                $("#video2").show();
                // $("#video2").show();
            })

            //监听播放序列动画2
            $.subscribe("playVideo2", function() {
                $(".phone").hide();
                $("#video2").css({
                    width: width,
                    height: height
                })
                var video = $("#video2")[0];
                video.play();

                video.addEventListener("ended",function(){
                    $("#video2").remove();
                    _self._showPhoneCall();
                })
            })
        })


        $('.first-page,.page,.phone,.phone-call,.load-mark').bind('touchstart', function() {
            return false;
        });
        //拨号界面事件绑定


        //点击播放
        $('.btn').bind("touchstart", function() {
            $('.load-mark').fadeOut();
            // debugger;
            $.publish("playVideo1");
        })

        $('.kbtn').each(function() {
            var ismove = false;
            var data = {};

            this.addEventListener('touchstart', function(e) {
                ismove = false;
                var ob = $(this).data('ob');
                $(this).css({
                    'background-position': '0 -' + ob + 'rem'
                });
            }, false, false);
            this.addEventListener('touchmove', function(e) {
                var touch = e.touches[0];
                data.ex = touch.pageX;
                data.ey = touch.pageY;
                if (Math.abs(data.sx - data.ex) > 20 || Math.abs(data.sy - data.ey) > 20) {
                    ismove = true;
                }
            }, false, false);
            this.addEventListener('touchend', function(e) {
                e.preventDefault();
                $(this).css({
                    'background-position': '0 0'
                });
                if (ismove) {
                    ismove = false;
                    return;
                }
                _self._press($(this).data('key'));
            }, false, false);
        });

        //添加
        $("#addBtn").bind('touchstart', function() {
                var text = $("#phoneTxt").text().replace(/-/g, '');
                if (!/^1[3|4|5|7|8]\d{9}$/.test(text)) {
                    $(".phone .poptips").text("请输入正确的手机号码！").addClass('showTip');
                    setTimeout(function() {
                        $(".phone .poptips").removeClass('showTip');
                    }, 1000)
                    return;
                }
                $.publish("playVideo2");

            })
            //删除
        $("#delBtn").bind('touchstart', function() {
            var text = $("#phoneTxt").text().replace(/-/g, '');
            text = text.substring(0, text.length - 1);
            if ('' === text) {
                $("#addBtn,#delBtn").hide();
            }
            $(".tips2").hide();

            if (text.length >= 9) {
                var temp = text;
                var array = temp.split('');
                array.splice(3, 0, '-');
                array.splice(8, 0, '-');
                text = array.join('');
            }
            $("#phoneTxt").text(text);
        })

        //挂断
        $(".endBtn").bind('touchstart',function(){
            $(".phone-call .poptips").addClass('showTip');
            setTimeout(function() {
                $(".phone-call .poptips").removeClass('showTip');
            }, 1000)
        })

        //接听
        $(".startBtn").bind('touchstart',function(){
            $(".phone-call").addClass("active");

            var audio = $('#audio')[0];

            var audioTimer = false;

            audio.addEventListener('timeupdate', function() {
                if (!audioTimer) {
                    audioTimer = true;
                    audio.currentTime = 0;
                }
            });
            audio.addEventListener('ended',function() {
                clearInterval(time);
                $(".phone-call").addClass("over");
                $(".phone-call .time").text("通话结束");
                setTimeout(function(){
                    $(".phone-call").hide();
                    _self._showLastPage();
                },1000)
            })
            audio.play();
            var index = 0;
            var time = setInterval(function(){
                index++;
                var text = index < 10 ? "0" + index : index + "";
                $(".time").text("00:" + text);
            },1000)
        })
    },
    //显示拨号界面
    _showPhone: function() {
        $(".phone").show();
        $("#phoneTxt").text("");
        $("#addBtn,#delBtn").hide();
    },

    //显示来电
    _showPhoneCall: function() {
        $(".page").hide();
        $(".phone-call").show();
        $("body,html,.phone-call").css("overflow","hidden");
    },

    //显示落地页
    _showLastPage: function() {
        $(".page").hide();
        $(".last-page").show();
        $(".last-page").css("overflow","hidden");
    },

    //按键处理
    _press: function(key) {

        switch (key) {
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
            case 0:
                var text = $("#phoneTxt").text().replace(/-/g, '');
                if (text.length >= 11) {
                    return;
                }
                if (text.length >= 10) {
                    this._showTip2();
                }
                $(".tips1").hide();
                if (text.length >= 9) {
                    var temp = text;
                    var array = temp.split('');
                    array.splice(3, 0, '-');
                    array.splice(8, 0, '-');
                    text = array.join('');
                }
                $("#phoneTxt").text(text + key);
                $("#addBtn,#delBtn").show();
                break;
            case 'call':
                var text = $("#phoneTxt").text().replace(/-/g, '');
                if (text.length >= 11) {
                    return;
                }
                $(".phone .poptips").text("请输入手机号码！").addClass('showTip');
                setTimeout(function() {
                    $(".phone .poptips").removeClass('showTip');
                }, 1000)
                break;
        }
    },
    _showTip2: function() {
        // $(".tips1").hide();
        $(".tips2").show();
    }
}

function _onorientationchange(e) {
    if (window.orientation == 90 || window.orientation == -90) {
        $("#forhorview").css("display", "block"); //显示竖屏浏览提示框
    } else { //竖屏下恢复默认显示效果
        $("#forhorview").css("display", "none");
    }
    document.documentElement.style.fontSize = document.documentElement.clientWidth / 7.5 + 'px';
    // page.fixVideo();
}
$(function() {
    page.init();

    window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", function(e) {
        _onorientationchange(e);
    }, false);
    _onorientationchange();
})
